<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>canvas</title>
</head>

<style>
    body {
        background-color: #000;
    }

    #myCanvas {
        border: 1px solid #ddd;
        margin: 100px auto;
        display: block;
    }
</style>

<body>
<canvas id="myCanvas" width="300" height="300"></canvas>
</body>


<script>
    function init(){
        let canvas = document.getElementById("myCanvas");
        let ctx = canvas.getContext("2d");
        draw(ctx);
    }

    function draw(ctx){
        setInterval(() => {
            drawScale(ctx); //绘制表盘
            drawAllHands(ctx); //绘制时分秒针
        },500)
        // requestAnimationFrame(function step(){
        //     drawScale(ctx); //绘制表盘
        //     drawAllHands(ctx); //绘制时分秒针
        //     requestAnimationFrame(step);
        // });
    }



    //画刻度
    function drawScale(ctx) {
        let pi = Math.PI;
        //清理掉所有内容
        ctx.clearRect(0, 0, 300, 300);
        //保存状态
        ctx.save();
        //移动至中心
        ctx.translate(150, 150);
        //绘制圆周
        ctx.beginPath();
        ctx.arc(0, 0, 150, 0, 2 * pi); 
        ctx.stroke();
        ctx.closePath(); 

        for (let i = 0; i < 60; i++) {
            ctx.save();
            //旋转 360deg / 60 = 6deg
            ctx.rotate(i * 6 * pi / 180);
            ctx.beginPath();
            ctx.moveTo(110, 0);
            ctx.lineTo(140, 0);
            ctx.lineWidth = i % 5 ? 2 : 4;
            ctx.strokeStyle = i % 5 ? "blue" : "red";
            ctx.stroke();
            ctx.closePath();
            ctx.restore();
        }
        //恢复至上一次的save状态
        ctx.restore();
    }


    /*绘制时分秒针*/
    function drawAllHands(ctx){
        let time = new Date();

        let s = time.getSeconds();
        let m = time.getMinutes();
        let h = time.getHours();

        let pi = Math.PI;
        let secondAngle = pi / 180 * 6 * s;  //计算出来s针的弧度
        let minuteAngle = pi / 180 * 6 * m + secondAngle / 60;  //计算出来分针的弧度
        let hourAngle = pi / 180 * 30 * h + minuteAngle / 12;  //计算出来时针的弧度

        drawPointer(hourAngle, 60, 6, "red",ctx);  //绘制时针
        drawPointer(minuteAngle, 106, 4, "green",ctx);  //绘制分针
        drawPointer(secondAngle, 129, 2, "blue",ctx);  //绘制秒针
    }

    //画指针
    function drawPointer(angle, len, width, color,ctx){
        ctx.save();
        //移动至中心
        ctx.translate(150, 150);
        ctx.rotate(-Math.PI / 2 + angle);
        ctx.beginPath();
        ctx.moveTo(-4, 0);
        ctx.lineTo(len, 0);  // 沿着x轴绘制针
        ctx.lineWidth = width;
        ctx.strokeStyle = color;
        ctx.lineCap = "round";
        ctx.stroke();
        ctx.closePath();
        ctx.restore();
    }



    init();



</script>




</html>